import { useState, useEffect, useRef, useContext } from 'react';
import { Layout, Table, Spin, message, Empty, Tabs, Button, Input } from 'antd';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { RightOutlined, DownOutlined, ReloadOutlined, FullscreenOutlined, EditOutlined, LeftOutlined } from '@ant-design/icons';
import { BsBoxSeam } from 'react-icons/bs';
import { TabsContext } from '../contexts/TabsContext';

// 导入产品图标
import productIcon from '../assets/产品图标.png';
import productGroupIcon from '../assets/产品组图标.png';

// 添加自定义CSS样式
const customStyles = `
  .horizontal-scroll-container {
    overflow-x: auto !important;
    overflow-y: auto !important;  /* 改为auto允许垂直滚动 */
    display: block !important;  /* 确保容器以块元素方式显示 */
  }
  
  .horizontal-scroll-container::-webkit-scrollbar {
    height: 8px !important;
    background-color: #f1f1f1 !important;
    display: block !important; /* 强制显示滚动条 */
  }
  
  .horizontal-scroll-container::-webkit-scrollbar-thumb {
    background-color: #c1c1c1 !important;
    border-radius: 4px !important;
  }
  
  .horizontal-scroll-container::-webkit-scrollbar-thumb:hover {
    background-color: #a8a8a8 !important;
  }
  
  /* 强制表格宽度，确保出现横向滚动条 */
  .ant-table-wrapper, .ant-table, .ant-table-container {
    min-width: 1500px !important;
  }
  
  /* 强制显示横向滚动条的类 */
  .show-scrollbar {
    overflow-x: auto !important;
  }
  
  /* 确保在所有数据行数情况下都显示横向滚动条 */
  .horizontal-scroll-container[data-rows-count="many"] {
    overflow-x: auto !important;
  }
  
  /* 正常行高 */
  .table-row-normal-height {
    height: 40px; /* 从48px减小到40px */
  }
  
  /* 紧凑行高（当数据行数较多时使用） */
  .table-row-compact-height {
    height: 28px !important; /* 从32px减小到28px */
    line-height: 28px !important; /* 从32px减小到28px */
  }
  
  /* 紧凑表格样式 */
  .compact-table .ant-table-thead > tr > th {
    padding: 6px 8px !important; /* Reduced padding from 8px to 6px 8px */
  }
  
  .compact-table .ant-table-tbody > tr > td {
    padding: 6px 8px !important; /* Reduced padding from 8px to 6px 8px */
  }
  
  /* 消除表格底部空白 */
  .ant-table-wrapper {
    margin-bottom: 0 !important;
  }

  .ant-table {
    margin: 0 !important;
  }
  
  /* 表格容器确保不出现额外空间 */
  .table-container-wrapper {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
  }
  
  /* 自定义分页样式 */
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px; /* Reduced top/bottom padding from 16px to 8px */
    border-top: 1px solid #e8e8e8;
    background: #fff;
    margin-bottom: 0; /* Ensure no bottom margin */
  }
  
  /* 表格标题区域样式 */
  .table-header-actions {
    padding: 8px 16px; /* Reduced padding from 16px to 8px 16px */
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  /* 操作按钮样式 */
  .action-buttons {
    display: flex;
    gap: 8px;
  }

  @media screen and (max-width: 576px) {
    .horizontal-scroll-container .ant-table-wrapper, 
    .horizontal-scroll-container .ant-table, 
    .horizontal-scroll-container .ant-table-container {
      min-width: 800px !important;
    }
    
    .ant-table-cell {
      padding: 4px !important;
      font-size: 12px !important;
    }
    
    .pagination-container {
      flex-direction: column;
      padding: 8px;
    }
    
    .pagination-container > div:last-child {
      margin-top: 8px;
    }
  }

  /* 表格样式优化 */
  .ant-table-container {
    border-bottom: none !important;
  }
  
  /* 确保表格行高一致性 */
  .ant-table-tbody > tr > td {
    transition: none !important; /* 防止过渡效果影响高度 */
  }
  
  /* 避免表格空白条 */
  .horizontal-scroll-container .ant-table-tbody > tr:last-child > td {
    border-bottom: none !important;
  }
`;

const { Content } = Layout;

const ProductLibrary = () => {
  // 使用TabsContext上下文
  const { addTab } = useContext(TabsContext);

  // 添加表格容器引用
  const tableContainerRef = useRef(null);
  const inputRef = useRef(null);

  const [loading, setLoading] = useState(false);
  const [treeData, setTreeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [categoryList, setCategoryList] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [productList, setProductList] = useState([]);
  const [showingProducts, setShowingProducts] = useState(false);
  const [hasSelectedCategory, setHasSelectedCategory] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [activeTab, setActiveTab] = useState('categoryDetail');
  const [categoryDetail, setCategoryDetail] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取分类树
  const fetchCategoryTree = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_category/tree`);
      if (response.data && response.data.code === 200) {
        const items = response.data.data.items || [];
        setTreeData(items);
        
        // 默认展开所有节点
        const allKeys = getAllKeys(items);
        setExpandedKeys(allKeys);
      } else {
        message.error('获取分类树失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取分类树错误:', error);
      message.error('获取分类树失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 递归获取所有节点的key，用于默认展开
  const getAllKeys = (data) => {
    let keys = [];
    data.forEach(item => {
      keys.push(item.id);
      if (item.children && item.children.length > 0) {
        keys = [...keys, ...getAllKeys(item.children)];
      }
    });
    return keys;
  };

  // 获取分类列表
  const fetchCategoryList = async (page = 1, size = 10, categoryId = null) => {
    setLoading(true);
    try {
      const params = {
        page,
        size
      };
      
      if (categoryId) {
        params.category_id = categoryId;
      }
      
      const response = await axios.get(`${API_BASE_URL}/api/product_category`, {
        params
      });
      
      if (response.data && response.data.code === 200) {
        // 确保使用API返回的实际数据
        const items = response.data.data.items || [];
        
        // 处理返回的数据，确保所有必要字段都存在
        const processedItems = items.map(item => ({
          ...item,
          key: item.id,
          // 如果某些字段不存在，提供默认值
          name: item.name || '未命名',
          code: item.code || '-',
          create_time: item.create_time || null,
          description: item.description || ''
        }));
        
        // 打印API返回的数据结构，便于调试
        console.log('API返回的数据结构:', items[0] ? Object.keys(items[0]) : '无数据');
        
        setCategoryList(processedItems);
        setPagination({
          ...pagination,
          current: page,
          pageSize: size,
          total: response.data.data.total || 0
        });
      } else {
        message.error('获取分类列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取分类列表错误:', error);
      message.error('获取分类列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取分类下的产品列表
  const fetchProductsByCategory = async (categoryId, page = 1, size = 10, includeSubcategories = false) => {
    if (!categoryId) return;
    
    setLoading(true);
    try {
      const params = {
        page,
        size,
        include_subcategories: includeSubcategories
      };
      
      const response = await axios.get(`${API_BASE_URL}/api/product_info/by_category/${categoryId}`, {
        params
      });
      
      if (response.data && response.data.code === 200) {
        const items = response.data.data.items || [];
        
        // 处理返回的数据，确保所有必要字段都存在
        const processedItems = items.map(item => ({
          ...item,
          key: item.id,
          name: item.name || '未命名',
          code: item.code || '-',
          create_time: item.create_time || null,
          description: item.description || ''
        }));
        
        console.log('产品列表数据:', processedItems);
        
        setProductList(processedItems);
        setPagination({
          ...pagination,
          current: page,
          pageSize: size,
          total: response.data.data.total || 0
        });
        
        // 设置为显示产品列表而非分类列表
        setShowingProducts(true);
        setHasSelectedCategory(true);
      } else {
        message.error('获取产品列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品列表错误:', error);
      message.error('获取产品列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 处理节点点击展开/折叠
  const handleToggle = (id) => {
    if (expandedKeys.includes(id)) {
      setExpandedKeys(expandedKeys.filter(key => key !== id));
    } else {
      setExpandedKeys([...expandedKeys, id]);
    }
  };

  // 处理节点选择
  const handleSelect = (id) => {
    setSelectedCategory(id);
    fetchCategoryDetail(id);  // 获取分类详情
    // 将在选项卡切换时获取产品列表
  };

  // 渲染树节点
  const renderTreeNodes = (data, level = 0) => {
    return data.map(item => {
      const isExpanded = expandedKeys.includes(item.id);
      const hasChildren = item.children && item.children.length > 0;
      
      // 计算缩进
      const indentStyle = { marginLeft: level * 24 + 'px' };
      
      return (
        <div key={item.id} className="custom-tree-node">
          <div 
            className="node-content" 
            style={{
              ...indentStyle,
              display: 'flex',
              alignItems: 'center',
              padding: '8px 0',
              cursor: 'pointer',
              whiteSpace: 'nowrap'
            }}
            onClick={() => handleSelect(item.id)}
          >
            {hasChildren ? (
              <span 
                className="tree-switcher"
                onClick={(e) => {
                  e.stopPropagation();
                  handleToggle(item.id);
                }}
                style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: '16px',
                  height: '16px'
                }}
              >
                {isExpanded ? 
                  <DownOutlined style={{ color: '#1766a3', fontSize: '12px' }} /> : 
                  <RightOutlined style={{ color: '#1766a3', fontSize: '12px' }} />
                }
              </span>
            ) : (
              <span style={{ width: '16px', display: 'inline-block' }}></span>
            )}
            <BsBoxSeam style={{ color: '#1766a3', margin: '0 8px', fontSize: '16px', flexShrink: 0 }} />
            <span style={{ whiteSpace: 'nowrap' }}>{item.name}</span>
          </div>
          
          {hasChildren && isExpanded && (
            <div className="tree-children">
              {renderTreeNodes(item.children, level + 1)}
            </div>
          )}
        </div>
      );
    });
  };

  // 处理表格分页变化
  const handleTableChange = (pagination, filters, sorter) => {
    if (showingProducts) {
      fetchProductsByCategory(selectedCategory, pagination.current, pagination.pageSize);
    } else {
      fetchCategoryList(pagination.current, pagination.pageSize, selectedCategory);
    }
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pagination.pageSize)) {
      setPagination({
        ...pagination,
        current: value
      });
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pagination.pageSize)) {
        if (showingProducts) {
          fetchProductsByCategory(selectedCategory, value, pagination.pageSize);
        }
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (pagination.current > 1) {
      const newPage = pagination.current - 1;
    if (showingProducts) {
        fetchProductsByCategory(selectedCategory, newPage, pagination.pageSize);
      }
    }
  };

  // 后一页
  const goNextPage = () => {
    if (pagination.current < Math.ceil(pagination.total / pagination.pageSize)) {
      const newPage = pagination.current + 1;
      if (showingProducts) {
        fetchProductsByCategory(selectedCategory, newPage, pagination.pageSize);
      }
    }
  };

  // 打开产品详情
  const openProductDetail = (record) => {
    if (!record || !record.id) return;
    
    // 打开一个新的页签，用于展示产品详情
    const tabKey = `productDetail-${record.id}`;
    const tabTitle = `${record.code || '产品'}`;
    addTab(tabKey, tabTitle, 'ProductDetail', { productId: record.id });
  };

  // 动态定义表格列以适应移动设备
  const getTableColumns = () => {
    const baseColumns = [
      {
        title: '标题',
        dataIndex: 'name',
        key: 'name',
        align: 'left',
        ellipsis: true,
        render: (text, record) => {
          // 根据产品类型选择不同的图标
          let useProductGroupIcon = false;
          
          if (record.product_type) {
            if (record.product_type === '零部件' || record.product_type === '成品' || 
                record.product_type === '零部件') {
              useProductGroupIcon = true;
            }
          }
          
          return (
            <span 
              style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }} 
              onClick={() => openProductDetail(record)}
            >
              <img 
                src={useProductGroupIcon ? productGroupIcon : productIcon} 
                alt="产品图标" 
                style={{ 
                  width: isMobile ? '12px' : '16px', 
                  height: isMobile ? '12px' : '16px', 
                  marginRight: isMobile ? '4px' : '8px',
                  verticalAlign: 'middle'
                }} 
              />
              <span>{text}</span>
            </span>
          );
        }
      },
      {
        title: '编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
            onClick={() => openProductDetail(record)}
          >
            {text || '-'}
          </span>
        )
      }
    ];
    
    // 移动端只显示核心列
    if (isMobile) {
      return [
        ...baseColumns,
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          align: 'center',
          ellipsis: true,
          render: (text) => {
            const statusMap = {
              'active': '发布',
              'inactive': '未发布',
              'draft': '草稿',
              'archived': '归档'
            };
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{statusMap[text] || text || '-'}</span>;
          }
        }
      ];
    }
    
    // 桌面端显示完整列
    return [
      ...baseColumns,
      {
        title: '分类',
        dataIndex: 'category_name',
        key: 'category_name',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '类型',
        dataIndex: 'product_type',
        key: 'product_type',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '当前版本',
        dataIndex: 'current_version',
        key: 'current_version',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        ellipsis: true,
        render: (text) => {
          const statusMap = {
            'active': '发布',
            'inactive': '未发布',
            'draft': '草稿',
            'archived': '归档'
          };
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{statusMap[text] || text || '-'}</span>;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => {
          if (!text) return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>-</span>;
          try {
            const date = new Date(text);
            if (!isNaN(date.getTime())) {
              return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>
                {date.toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit',
                  hour12: false
                }).replace(/\//g, '-')}
              </span>;
            }
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text}</span>;
          } catch (error) {
            console.error('日期格式化错误:', error);
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>;
          }
        }
      },
      {
        title: '说明',
        dataIndex: 'description',
        key: 'description',
        align: 'left',
        ellipsis: true,
        render: (text) => (
          <div style={{
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            width: '100%',
            paddingRight: '8px'
          }}>
            {text || '-'}
          </div>
        )
      }
    ];
  };

  // 根据数据行数动态计算行高的类名
  const getRowClassName = () => {
    const dataLength = showingProducts ? productList.length : categoryList.length;
    // 更改逻辑：当数据达到6行或更多时使用紧凑行高，确保10行时紧凑显示
    if (dataLength >= 6 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // Add useEffect for wheel event - 删除对滚轮事件的自定义处理
  useEffect(() => {
    // 不再添加滚轮事件监听，使用默认的浏览器滚动行为
  }, [productList.length]);

  // 组件挂载时加载数据
  useEffect(() => {
    fetchCategoryTree();
  }, []);

  // 处理选项卡切换
  const handleTabChange = (activeKey) => {
    setActiveTab(activeKey);
    if (activeKey === 'productList' && selectedCategory) {
      fetchProductsByCategory(selectedCategory, 1, pagination.pageSize);
    }
  };

  // 获取产品分类详情
  const fetchCategoryDetail = async (categoryId) => {
    if (!categoryId) return;
    
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_category/${categoryId}`);
      
      if (response.data && response.data.code === 200) {
        setCategoryDetail(response.data.data);
        setActiveTab('categoryDetail');  // 默认显示分类详情tab
        setHasSelectedCategory(true);
      } else {
        message.error('获取分类详情失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取分类详情错误:', error);
      message.error('获取分类详情失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout className={`product-library-container ${isMobile ? 'mobile-layout' : ''}`}>
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      <Content style={{ padding: '0', height: '100%' }}>
        <div style={{ 
          display: 'flex', 
          height: '100%',
          flexDirection: isMobile ? 'column' : 'row' 
        }}>
          {/* 左侧分类树 */}
          <div style={{ 
            width: isMobile ? '100%' : '260px', 
            minWidth: isMobile ? '100%' : '260px',
            flexShrink: 0,
            height: isMobile ? 'auto' : '100%', 
            maxHeight: isMobile ? '200px' : 'none',
            padding: isMobile ? '8px' : '16px', 
            borderRight: isMobile ? 'none' : '1px solid #e8e8e8',
            borderBottom: isMobile ? '1px solid #e8e8e8' : 'none',
            background: '#fff',
            overflowX: 'auto',
            overflowY: 'hidden'
          }}>
            <div style={{ 
              marginBottom: isMobile ? '8px' : '16px', 
              fontWeight: 'bold', 
              fontSize: isMobile ? '14px' : '16px', 
              color: '#1766a3',
              display: 'flex',
              alignItems: 'center'
            }}>
              <BsBoxSeam style={{ 
                fontSize: isMobile ? '14px' : '18px', 
                marginRight: isMobile ? '4px' : '8px', 
                color: '#1766a3' 
              }} />
              <span>产品分类</span>
            </div>
            <Spin spinning={loading}>
              <div className="custom-tree" style={{
                maxHeight: isMobile ? '150px' : 'calc(100vh - 190px)',
                overflowX: 'hidden',
                overflowY: 'auto'
              }}>
                {treeData.length > 0 ? (
                  renderTreeNodes(treeData)
                ) : (
                  <div className="empty-tree">暂无分类数据</div>
                )}
              </div>
            </Spin>
          </div>
          
          {/* 右侧内容区域 - 条件渲染分类列表或产品列表 */}
            <div style={{ 
              flex: 1, 
              padding: isMobile ? '8px' : '16px', 
              paddingBottom: 0,
              display: 'flex',
              flexDirection: 'column',
              height: isMobile ? 'calc(100vh - 350px)' : 'calc(100vh - 100px)',
              overflowX: 'hidden',
              overflowY: 'auto' // 修改为auto允许垂直滚动
            }}>
              <Spin spinning={loading}>
                {hasSelectedCategory ? (
                  <div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    height: '100%',
                    border: '1px solid #e8e8e8',
                    background: '#fff',
                    overflow: 'hidden' /* 添加overflow: hidden防止内容溢出 */
                  }}>
                  {/* 选项卡头部 */}
                    <div style={{
                      display: 'flex',
                    justifyContent: 'space-between',
                      borderBottom: '1px solid #e8e8e8',
                    background: '#fafafa'
                    }}>
                      <div style={{
                      display: 'flex'
                      }}>
                        <div 
                          onClick={() => handleTabChange('categoryDetail')} 
                          style={{ 
                            padding: '12px 16px',
                            cursor: 'pointer',
                            position: 'relative',
                            color: activeTab === 'categoryDetail' ? '#1766a3' : 'inherit',
                            fontWeight: activeTab === 'categoryDetail' ? 'bold' : 'normal'
                          }}
                        >
                          分类详情
                          {activeTab === 'categoryDetail' && (
                            <div style={{
                              position: 'absolute',
                              bottom: 0,
                              left: 0,
                              right: 0,
                              height: '2px',
                              background: '#1766a3'
                            }}></div>
                          )}
                        </div>
                        <div 
                          onClick={() => handleTabChange('productList')} 
                          style={{ 
                            padding: '12px 16px',
                            cursor: 'pointer',
                            position: 'relative',
                            color: activeTab === 'productList' ? '#1766a3' : 'inherit',
                            fontWeight: activeTab === 'productList' ? 'bold' : 'normal'
                          }}
                        >
                          产品列表
                          {activeTab === 'productList' && (
                            <div style={{
                              position: 'absolute',
                              bottom: 0,
                              left: 0,
                              right: 0,
                              height: '2px',
                              background: '#1766a3'
                            }}></div>
                          )}
                        </div>
                      </div>
                      <div style={{
                        display: 'flex',
                        alignItems: 'center'
                      }}>
                        {activeTab === 'productList' && (
                          <>
                            <Button 
                              type="text" 
                              icon={<ReloadOutlined />} 
                              size="small"
                              title="刷新"
                            onClick={() => fetchProductsByCategory(selectedCategory, 1, pagination.pageSize)}
                            />
                            <Button 
                              type="text" 
                              icon={<FullscreenOutlined />} 
                              size="small"
                              title="最大化"
                            />
                          </>
                        )}
                        <Button 
                          type="text" 
                          icon={<EditOutlined />} 
                          size="small"
                          title="编辑"
                        />
                      </div>
                    </div>
                    
                    {/* 选项卡内容 */}
                    {activeTab === 'categoryDetail' ? (
                      // 分类详情内容
                      <div style={{ padding: '16px', background: '#fff' }}>
                        {categoryDetail && (
                          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '16px', alignItems: 'center' }}>
                            <div style={{ fontWeight: 'bold', textAlign: 'right' }}>编码:</div>
                            <div>{categoryDetail.code || '-'}</div>
                            
                            <div style={{ fontWeight: 'bold', textAlign: 'right' }}>标题:</div>
                            <div>{categoryDetail.name || '-'}</div>
                            
                            <div style={{ fontWeight: 'bold', textAlign: 'right' }}>层级:</div>
                            <div>{categoryDetail.level || '-'}</div>
                            
                            <div style={{ fontWeight: 'bold', textAlign: 'right' }}>说明:</div>
                            <div>{categoryDetail.description || '-'}</div>
                            
                            <div style={{ fontWeight: 'bold', textAlign: 'right' }}>创建时间:</div>
                            <div>{categoryDetail.create_time ? new Date(categoryDetail.create_time).toLocaleString('zh-CN') : '-'}</div>
                            
                            <div style={{ fontWeight: 'bold', textAlign: 'right' }}>更新时间:</div>
                            <div>{categoryDetail.update_time ? new Date(categoryDetail.update_time).toLocaleString('zh-CN') : '-'}</div>
                          </div>
                        )}
                      </div>
                    ) : (
                      // 产品列表内容
                      <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        flex: 1,
                        overflowX: 'hidden',
                        overflowY: 'auto', /* 修改为auto允许垂直滚动 */
                        height: '100%' /* Ensure this container takes full available height */
                      }}>
                      <div className="table-header-actions">
                        <div>
                          <h3 style={{ margin: 0, fontSize: '14px' }}>产品列表</h3>
                        </div>
                        <div className="action-buttons">
                          {/* 此处可以添加操作按钮 */}
                        </div>
                      </div>
                        <div 
                          ref={tableContainerRef}
                          className="horizontal-scroll-container table-container-wrapper"
                          data-rows-count={productList.length > 10 ? "many" : "few"}
                          style={{
                            width: '100%',
                            flex: 1,
                            overflowX: productList.length > 0 ? 'auto' : 'hidden',
                            overflowY: 'auto', // 修改为auto以允许垂直滚动
                            display: 'block',
                            whiteSpace: 'nowrap',
                            position: 'relative',
                            margin: 0,
                            padding: 0
                          }}
                        >
                          <div style={{ 
                            minWidth: isMobile ? '800px' : 'auto', 
                            width: isMobile ? '800px' : '100%', 
                            position: 'relative',
                            height: '100%',
                            margin: 0,
                            padding: 0
                          }}>
                            <Table
                              className={`data-table ${productList.length >= 6 || isMobile ? 'compact-table' : ''}`}
                              columns={getTableColumns()}
                              dataSource={productList}
                              rowKey="id"
                              pagination={false}
                              onChange={handleTableChange}
                              size="small"
                              bordered={true}
                              scroll={{ x: productList.length > 0 ? (isMobile ? 800 : 'max-content') : undefined }}
                              tableLayout="fixed"
                              rowClassName={getRowClassName}
                              style={{ margin: 0 }}
                            />
                          </div>
                        </div>
                        
                      {/* 自定义分页，参考FeatureMapping.jsx */}
                      <div className="pagination-container" style={{ 
                        marginTop: 'auto',
                        flexShrink: 0 /* 确保分页不会被压缩 */
                      }}> {/* Added marginTop: 'auto' to push it to bottom */}
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pagination.pageSize)} 页</span>
                        </div>
                        
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <Button 
                            icon={<LeftOutlined />}
                            onClick={goPrevPage}
                                disabled={pagination.current <= 1}
                            style={{ marginRight: '8px' }}
                          />
                          
                          <Input
                            ref={inputRef}
                            style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                            value={pagination.current}
                            onChange={handlePageInputChange}
                            onKeyPress={handlePageInputKeyPress}
                          />
                          
                          <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pagination.pageSize)}</span>
                          
                          <Button 
                            icon={<RightOutlined />}
                            onClick={goNextPage}
                                disabled={pagination.current >= Math.ceil(pagination.total / pagination.pageSize)}
                            style={{ marginLeft: '8px', marginRight: '8px' }}
                          />
                          
                          <span style={{ marginLeft: '8px' }}>
                            10 / 页
                              </span>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  // 未选择分类，显示提示信息
                  <div className="table-container" style={{
                    border: '1px solid #e8e8e8',
                    position: 'relative',
                    width: '100%',
                    flex: 1,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    background: '#fff'
                  }}>
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description={
                        <span style={{ fontSize: isMobile ? '14px' : '16px', color: '#999' }}>
                          请点击{isMobile ? '上方' : '左侧'}产品分类查看对应产品列表
                        </span>
                      }
                    />
                  </div>
                )}
              </Spin>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default ProductLibrary; 